package com.fsp.blog.service.iml;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fsp.blog.dao.TagMapper;
import com.fsp.blog.pojo.Tag;
import com.fsp.blog.service.TagsService;
import com.fsp.blog.vo.Result;
import com.fsp.blog.vo.TagVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author fushengping
 * @className TagsServiceImpl
 * @description
 * @date 2021/11/7 10:33
 */
@Service
public class TagsServiceImpl implements TagsService {

    @Autowired
    private TagMapper tagMapper;

    public TagVo copy(Tag tag) {
        TagVo tagVo = new TagVo();
        BeanUtils.copyProperties(tag, tagVo);
        return tagVo;
    }
    public List<TagVo> copyList(List<Tag> tagList) {
        List<TagVo> tagVos = new ArrayList<>();
        for (Tag tag : tagList) {
            tagVos.add(copy(tag));
        }
        return tagVos;
    }
    @Override
    public List<TagVo> findTagsByArticleId(Long articleId) {
        List<Tag> tags = tagMapper.findTagsByArticleId(articleId);
        //单独一个时直接BeanUtils.copyProperties(tag, tagVo);但这里是数组
        return copyList(tags);
    }

    @Override
    public Result listHotTags(int limit) {
        /**
         * 最热标签的实现:标签拥有的文章数最多
         * 1.先对标签表根据id进行分组
         * 2.对分组后的数据进行排序，最多的为最热标签
         * 3.根据最热标签id,来查询name
         */
        List<Long> tagsIds = tagMapper.findTagsHotIds(limit);
        //安全起见，需判断tagsIds是否为空
        if (CollectionUtils.isEmpty(tagsIds)) {
            return Result.success(Collections.emptyList());//返回空
        }
        //2.查询tag_name,等相关信息
        List<Tag> tagList = tagMapper.findTagsByTagsIds(tagsIds);
        return Result.success(tagList);
    }

    @Override
    public Result findAll() {
        LambdaQueryWrapper<Tag> queryWrapper = new LambdaQueryWrapper<>();
        //用多少查多少
        queryWrapper.select(Tag::getId,Tag::getTagName);
        List<Tag> tags = this.tagMapper.selectList(queryWrapper);
        return Result.success(copyList(tags));
    }

    @Override
    public Result findAllDetail() {
        List<Tag> tags = this.tagMapper.selectList(new LambdaQueryWrapper<>());
        return Result.success(copyList(tags));
    }

    @Override
    public Result findDetailById(Long id) {
        Tag tag = tagMapper.selectById(id);
        return Result.success(copy(tag));
    }
}
